<link rel="stylesheet" href="assets/js/ztree/css/zTreeStyle/zTreeStyle.css" type="text/css">
<div class="row">
    <div class="col-lg-12 col-sm-12 col-xs-12">
        <div class="widget">
            <div class="widget-header bordered-bottom theme">
                <span class="widget-caption">园所默认角色、菜单、操作权限维护</span>
            </div>
            <div class="widget-body">
                <div class="alert alert-warning fade in">
                    <button class="close" data-dismiss="alert">×</button>
                    <p><strong>Error!</strong>&nbsp;&nbsp;&nbsp;&nbsp;修改园所默认菜单及默认操作权限相关配置是一个十分危险的操作，若您并不熟悉相关角色、菜单及菜单相关操作权限的具体作用，请谨慎使用该功能。
                    </p>
                </div>
                <div class="alert alert-info fade in">
                    <button class="close" data-dismiss="alert">×</button>
                    <i class="fa-fw fa fa-info"></i>
                    <strong>注意：</strong><br>
                    <span class="badge badge-sky graded margin-right-5">1</span>按钮【更新临时配置】并不是把参数直接保存到数据库了，只是更新当前界面配置的信息。<br>
                    <span class="badge badge-sky graded margin-right-5">2</span>按钮 【保存配置】是将所有配置保存到数据库中。<br>
                    <span class="badge badge-sky graded margin-right-5">3</span>对每一个角色设置完任何一个菜单或则操作权限都要进行【更新临时配置】操作，否则配置将不会更新。<br>
                    <span class="badge badge-sky graded margin-right-5">4</span>请谨慎对各个角色都配置好相关菜单和操作权限后再进行【保存配置】操作。
                </div>
                <div id="registration-form">
                    <form role="form">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-group text-align-center">
                                    <label for="roles">Default Roles</label>
                                    <input type="hidden" id="roles">
                                    <select id="defaultRoles" style="width: 40%;">
                                        <option value="园长" selected>园长</option>
                                        <option value="教务">教务</option>
                                        <option value="顾问主管">顾问主管</option>
                                        <option value="顾问">顾问</option>
                                        <option value="财务">财务</option>
                                        <option value="教学主管">教学主管</option>
                                        <option value="教师">教师</option>
                                    </select>
                                    <a class="btn btn-palegreen btn-xs" href="javascript:void(0);" id="addRole"><i
                                            class="fa fa-plus"></i>添加新默认角色</a>
                                    <a class="btn btn-danger margin-right-10 float-right" id="saveConfig"><i
                                            class="fa fa-save"></i>保存配置</a>
                                    <a class="btn btn-success margin-right-10 float-right"
                                       onclick="$('#tempSave').click()"><i class="fa fa-life-saver"></i>更新临时配置</a>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-sm-4">
                                <label>Roles For Menus </label>
                                <input id="selectedMenuIds" type="hidden" readonly="readonly" value=""
                                       class="form-control" onclick="showMenu();"/>
                                <div id="menuContent" class="menuContent">
                                    <ul id="sysMenuTree" class="ztree menuTree"
                                        style="border:1px solid #CCCCCC;width:100%;overflow-y:scroll;overflow-x:auto;"></ul>
                                </div>
                            </div>
                            <div class="col-sm-4">
                                <label>Selected Menu preview</label>
                                <div style="border: 1px solid #ccc; border-bottom:none;overflow: auto;"
                                     id="selectedMenus">
                                    <ul id="selectedSysMenuTree" class="ztree prevMenuTree" style="width:100%;"></ul>
                                </div>
                                <textarea id="config"
                                          style="width: 100%; background-color:#000000; color: #ffffff;border-color: #000000; resize: none;"
                                          readonly="readonly"><#if  tssSchoolDefaultRoleConfigJson.id??>${tssSchoolDefaultRoleConfigJson.value}<#else>当前暂存配置参数预览</#if></textarea>
                            </div>
                            <div class="col-sm-4">
                                <label>Menu For Handle Permissions Setting</label>
                                <div style="border: 1px solid #ccc; min-height: 200px;padding-bottom: 40px;"
                                     id="handlePermissions">

                                </div>
                                <a class="hidden" id="tempSave"></a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="assets/js/select2/select2.js"></script>
<script src="assets/js/validation/bootstrapValidator_init.js"></script>
<script src="assets/js/ztree/jquery.ztree.all.js"></script>
<script>

    $("#roles").val($("#defaultRoles").val());

    $(".menuTree").height($(window).height() - 420);
    $("#handlePermissions").height($(window).height() - 450);
    $(".prevMenuTree,#config").height(($(window).height() - 420) / 2);

    (function () {
        var defaultConfig;//当前配置
        var oldRoleConfig = $("#config").val(); //历史配置
        if (oldRoleConfig) {
            if (!/^\s*$/.test(oldRoleConfig.trim()) && oldRoleConfig.trim() != "当前暂存配置参数预览") {
                try{
                    defaultConfig = JSON.parse(oldRoleConfig.trim());
                    $("#config").val(formatJson(defaultConfig));
                }catch (e){}
            }
        }
        var setting = {
            check: {
                enable: true,
                autoCheckTrigger: true
            },
            view: {
                beforeClick: false,
                selectedMulti: false,
                dblClickExpand: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                beforeClick: beforeClick,
                onCheck: onCheck
            }
        };
        var settingForSelectedMenu = {
            view: {
                dblClickExpand: true
            },
            data: {
                simpleData: {
                    enable: true
                }
            },
            callback: {
                onClick: loadHandlePermission
            }
        };

        var lastLevelMenu;
        Http.get(ctx + "/permissionSetting/getAllMenus.do", null, function (result) {
            if (result.resCode == 200) {
                if (result.data) {
                    var data = result.data;
                    var zNodes = new Array();
                    for (var i = 0, len = data.length; i < len; i++) {
                        var menu = data[i];
                        menu.pId = menu.pId ? menu.pId : 0;
                        var node = {
                            id: menu.id,
                            pId: menu.pId,
                            name: menu.name,
                            open: true,
                        };
                        zNodes.push(node);
                    }
                    if (result.extendParams) {
                        if (result.extendParams.lastLevelMenuPermissions) {
                            lastLevelMenu = result.extendParams.lastLevelMenuPermissions;
                            for (var i = 0, len = lastLevelMenu.length; i < len; i++) {
                                var menu = lastLevelMenu[i];
                                var node = {
                                    id: menu.id,
                                    pId: menu.pId,
                                    name: menu.name
                                };
                                zNodes.push(node);
                            }
                        }
                    }
                    $.fn.zTree.init($("#sysMenuTree"), setting, zNodes);
                    $("#defaultRoles").change();
                }
            } else {
                logger.error(result.resMsg);
            }
        }, function () {
            logger.error("加载菜单失败!");
        }, "json");

        function beforeClick(treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("sysMenuTree");
            zTree.checkNode(treeNode, !treeNode.checked, null, true);
            return false;
        }

        //所有已经选中节点
        var selectedSysMenuTreeNodes = new Array();

        function onCheck(e, treeId, treeNode) {
            var zTree = $.fn.zTree.getZTreeObj("sysMenuTree"),
                nodes = zTree.getCheckedNodes(true),
                vals = new Array();
            for (var i = 0, l = nodes.length; i < l; i++) {
                for (var j = 0, len = lastLevelMenu.length; j < len; j++) {
                    var menu = lastLevelMenu[j];
                    if (menu.id == nodes[i].id) {
                        vals.push(nodes[i].id);
                    }
                }
            }
            //转换成新树节点
            selectedSysMenuTreeNodes = new Array();
            converNode(nodes, true);
            //记录选中的最后一级节点id
            var cityObj = $("#selectedMenuIds");
            cityObj.val(vals.join());
            //初始化菜单预览树
            $.fn.zTree.init($("#selectedSysMenuTree"), settingForSelectedMenu, selectedSysMenuTreeNodes);
            $("#handlePermissions").html("");
        }

        function converNode(nodes, isChecked) {
            for (var i = 0, l = nodes.length; i < l; i++) {
                var node = nodes[i];
                if (isChecked == true) {
                    if (!node.checked) {
                        continue;
                    }
                }
                var newNode = {
                    id: node.id,
                    pId: node.pId,
                    name: node.name
                };
                if (node.children) {
                    newNode.open = true;
                    newNode.nocheck = true;
                    converNode(node.children, isChecked);
                }
                var isExists = false;
                for (var j = 0, len = selectedSysMenuTreeNodes.length; j < len; j++) {
                    if (selectedSysMenuTreeNodes[j].id == node.id) {
                        isExists = true;
                    }
                }
                if (!isExists) {
                    selectedSysMenuTreeNodes.push(newNode);
                }
            }
        }

        function loadHandlePermission(e, treeId, treeNode) {
            if (treeNode.children) {
                return;
            }
            Http.get(ctx + "/permissionSetting/getMenuHandlePermission.do", {
                menuPermissionId: treeNode.id
            }, function (html) {
                $("#handlePermissions").html(html);
            }, function () {
                logger.error("加载菜单失败!");
            }, "html");
        }

        function genRoleConfig() {
            $("#defaultRoles").children().each(function () {
                var roleName = $(this).val();
                if (roleName) {
                    if (!defaultConfig[roleName]) {
                        defaultConfig[roleName] = new Array();
                    }
                }
            });
        }

        function genMenuConfig() {
            var selectedSysMenuTree = $.fn.zTree.getZTreeObj("selectedSysMenuTree");
            if (selectedSysMenuTree) {
                var prevMenuTreeNode = selectedSysMenuTree.getNodes();
                //新设置的菜单id
                var newMenuIds = new Array();
                //转换成新树节点
                selectedSysMenuTreeNodes = new Array();
                converNode(prevMenuTreeNode, false);
                //找到最后一层菜单节点
                var roleName = $("#roles").val();
                if (!defaultConfig) {
                    defaultConfig = {};
                }
                if (!defaultConfig[roleName]) {
                    defaultConfig[roleName] = new Array();
                }
                for (var i = 0, len_i = selectedSysMenuTreeNodes.length; i < len_i; i++) {
                    for (var j = 0, len_j = lastLevelMenu.length; j < len_j; j++) {
                        var menuId = lastLevelMenu[j].id;
                        var selectedMenuTreeNodeId = selectedSysMenuTreeNodes[i].id;
                        var selectedMenuTreeNodeName = selectedSysMenuTreeNodes[i].name;
                        if (selectedMenuTreeNodeId == menuId) {
                            newMenuIds.push(menuId);
                            var isExists = false;
                            for (var j = 0, len = defaultConfig[roleName].length; j < len; j++) {
                                if (defaultConfig[roleName][j].menuId == menuId) {
                                    isExists = true;
                                    break;
                                }
                            }
                            if (!isExists) {
                                defaultConfig[roleName].push({
                                    menuId: menuId,
                                    menuName: selectedMenuTreeNodeName,
                                    handleIds: []
                                });
                            }
                            break;
                        }
                    }
                }
                //删除历史
                var oldConfig = defaultConfig[roleName];
                var newConfig = new Array();
                for (var j = 0, len = oldConfig.length; j < len; j++) {
                    var isExists = false;
                    for (var i = 0, len = newMenuIds.length; i < len; i++) {
                        var menuId = newMenuIds[i];
                        if (oldConfig[j].menuId == menuId) {
                            isExists = true;
                            break;
                        }
                    }
                    if (isExists) {
                        newConfig.push(oldConfig[j]);
                    }
                }
                defaultConfig[roleName] = newConfig;
                oldConfig = null;
            }
        }

        function genHandlePermissionConfig(roleName) {
            var menuId = $("#handlePermissionAllotForm [name='menuPermissionId']").val();
            if (menuId) {
                for (var j = 0, len = defaultConfig[roleName].length; j < len; j++) {
                    if (defaultConfig[roleName][j].menuId == menuId) {
                        defaultConfig[roleName][j].handleIds = new Array();
                        break;
                    }
                }
                $("#handlePermissionAllotForm :checkbox:checked").each(function () {
                    var handlePermissionId = $(this).val();
                    for (var j = 0, len = defaultConfig[roleName].length; j < len; j++) {
                        if (defaultConfig[roleName][j].menuId == menuId) {
                            var isExists = false;
                            for (var i = 0, len_i = defaultConfig[roleName][j].handleIds.length; i < len_i; i++) {
                                if (defaultConfig[roleName][j].handleIds[i] == handlePermissionId) {
                                    isExists = true;
                                    break;
                                }
                            }
                            if (!isExists) {
                                defaultConfig[roleName][j].handleIds.push(handlePermissionId);
                            }
                            break;
                        }
                    }
                });
            }
        }

        function genConfig() {
            var roleName = $("#roles").val();
            if (roleName) {
                //更新角色配置参数
                genRoleConfig();
                //更新菜单配置参数
                genMenuConfig();
                //更新操作权限设置参数
                genHandlePermissionConfig(roleName);
            }
            $("#config").val(formatJson(defaultConfig));
        }

        $("#addRole").click(function () {
            bootbox.prompt("请输入角色名称", function (roleName) {
                if (roleName) {
                    if ($("#roles").find("[value='" + roleName + "']").size() > 0) {
                        alert("角色已经存在!");
                    } else {
                        $("#defaultRoles").append('<option value="' + roleName + '">' + roleName + '</option>');
                    }
                }
            });
        });

        $("#defaultRoles").change(function () {
            var $nowSetRole = $("#roles");
            $nowSetRole.val(this.value);
            var treeObj = $.fn.zTree.getZTreeObj("sysMenuTree");
            treeObj.checkAllNodes(false);
            $("#handlePermissions,#selectedSysMenuTree").html("");
            //选中当前配置中设置的菜单
            if (!defaultConfig) {
                defaultConfig = {};
            }
            var config = defaultConfig;
            var roleName = $("#defaultRoles").val();
            if (config[roleName]) {
                for (var i = 0, len = config[roleName].length; i < len; i++) {
                    var menuId = config[roleName][i].menuId;
                    treeObj.checkNode(treeObj.getNodeByParam("id", menuId, null), true, true);
                }
            }
        })

        $("#tempSave").click(function () {
            genConfig();
        });

        $("#saveConfig").click(function () {
            if (defaultConfig) {
                if (confirm("修改园所默认菜单及默认操作权限相关配置是一个十分危险的操作，若您并不熟悉相关角色、菜单及菜单相关操作权限的具体作用，请谨慎使用该功能。确认要继续修改吗？")) {
                    Http.post("permissionSetting/saveDefaultRoleConfig.do", defaultConfig, function (result) {
                        if (result.resCode == 200) {
                            logger.info("保存配置成功!", true);
                        } else {
                            logger.error(res.resMsg);
                        }
                    }, function () {
                        logger.error("保存失败!");
                    }, "json", true);
                }
            } else {
                logger.error("请先进行配置!")
            }
        });
    })();
</script>